package com.crl.module.cmpRpc.behavior
{
	import com.crl.events.RemoteOperationEvent;
	import com.crl.module.cmpRpc.model.RequestVO;
	import com.crl.module.cmpRpc.parsers.IRemoteObjectParser;
	import com.crl.utils.StringUtil;
	
	import flash.system.ApplicationDomain;
	import flash.utils.Dictionary;
	
	
	/**
	 *  不同的请求策略;
	 * @author crl
	 * 
	 */	
	public class AbstractRequestBehavior implements IRequestBehavior
	{
		protected var _method:String;
		protected var _parms:Object;
		
		protected var token:RemoteToken;
		
		private var _requestvo:RequestVO;
		
	
		public function AbstractRequestBehavior()
		{
			token=new RemoteToken();
		}
		
		public function request(o:Object=null):RemoteToken
		{
			
			var voParm:Dictionary=_requestvo.parms;
			var pro:String;
			for(var key:String in voParm){
				pro=voParm[key];
				
				if(o.hasOwnProperty(pro)){
					voParm[key]=o[pro];
				}else{
					trace(StringUtil.substitute("请求方法:{0} 的配置参数:{1} 不存在",_requestvo.method,pro))
				}
			}
			
			_parms=voParm;
			
			return token;
		}
		
		public function set requestvo(value:RequestVO):void{
			this._requestvo=value;
			
			this._method=value.method;
		}
		public function get requestvo():RequestVO{
			return this._requestvo;
			
			
		}
		
		
		public function resultHandler(o:Object):void{
			var data:Object=parse(o);
			
			token.dispatchEvent(new RemoteOperationEvent(RemoteOperationEvent.SUCCESED,data));
		}
		
		
		public function errorHandler(message:String):void{
			token.dispatchEvent(new RemoteOperationEvent(RemoteOperationEvent.FAILED,null,message));
		}
		
		
		/**
		 * 对于parser 及mapping的处理; 
		 * @param data
		 * @return 
		 * 
		 */		
		private function parse(data:Object):Object {
			
			if(_requestvo.parser){
				var cls:Class
				if(domain.hasDefinition(_requestvo.parser)){
					cls=domain.getDefinition(_requestvo.parser) as Class;
				}
				if(cls){
					var parser:IRemoteObjectParser=new cls();
					if(parser==null){
						return data;
					}
					
					cls=null
					if(_requestvo.mapping != ""){
						if(domain.hasDefinition(_requestvo.mapping)==false){
							trace(StringUtil.substitute("远程映射对像 {0}不存在",_requestvo.mapping));
						}else{
							cls=domain.getDefinition(_requestvo.mapping) as Class;
						}
					}
					return parser.parse(data,cls);
				}
			}
			
			
			return data;
		}
		
		
		/**
		 * 取得 parser 及mapping的 所在域;
		 * @return 
		 * 
		 */		
		protected function get domain():ApplicationDomain{
			return  ApplicationDomain.currentDomain;
		}
		
	}
}